package ute.mvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.Question;
import ute.mvc.model.QuestionPool;
import ute.mvc.model.TestPart;

@Repository("questionDAO")
public class QuestionDAOImpl implements QuestionDAO {
	@Autowired
	SessionFactory sessionFactory;

	public void addQuestion(Question question) {
		sessionFactory.getCurrentSession().save(question);
	}

	public void updateQuestion(Question question) {
		sessionFactory.getCurrentSession().merge(question);
	}

	public void deleteQuestion(Question question) {
		sessionFactory.getCurrentSession().delete(question);
	}

	//Vinh
	public String getMaxIdInPool(QuestionPool pool) {
		// TODO Auto-generated method stub
		Criteria criteria = sessionFactory.getCurrentSession()
				.createCriteria(Question.class)
				.add(Restrictions.eq("questionPool", pool))
				.setProjection(Projections.max("questionId"));
		String maxId = (String)criteria.uniqueResult();
		return maxId;
	}

	public Question getQuestion(String questionId) {
		// TODO Auto-generated method stub
		return (Question) sessionFactory.getCurrentSession().get(Question.class, questionId);
	}

	public String getMaxIdInPart(TestPart part) {
		// TODO Auto-generated method stub
		Criteria criteria = sessionFactory.getCurrentSession()
				.createCriteria(Question.class)
				.add(Restrictions.eq("testPart", part))
				.setProjection(Projections.max("questionId"));
		String maxId = (String)criteria.uniqueResult();
		return maxId;
	}

	@SuppressWarnings("unchecked")
	public List<Question> getQuestionInPart(TestPart part) {
		// TODO Auto-generated method stub
		List<Question> list= sessionFactory.getCurrentSession()
				.createCriteria(Question.class)
				.add(Restrictions.eq("testPart", part)).list();
		return list;
	}

}
